package com.example.finalproject.experiments.thread

import android.app.AlertDialog
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.example.finalproject.ui.theme.FinalProjectTheme
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class ThreadExperimentActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FinalProjectTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    ThreadDemoScreen()
                }
            }
        }
    }
}

@Composable
fun ThreadDemoScreen() {
    val context = LocalContext.current
    var isLoading by remember { mutableStateOf(false) }
    var bitmap by remember { mutableStateOf<Bitmap?>(null) }
    val imageUrl = "https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=800&q=80"

    fun downloadImage(urlStr: String): Bitmap? {
        return try {
            val url = URL(urlStr)
            val conn = url.openConnection() as HttpURLConnection
            conn.doInput = true
            conn.connect()
            val input: InputStream = conn.inputStream
            BitmapFactory.decodeStream(input)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        if (bitmap != null) {
            AndroidView(
                factory = { ImageView(it) },
                modifier = Modifier
                    .width(300.dp)
                    .height(200.dp)
                    .padding(bottom = 24.dp),
                update = { imageView ->
                    imageView.setImageBitmap(bitmap)
                    imageView.scaleType = ImageView.ScaleType.FIT_CENTER
                }
            )
        } else {
            Box(
                modifier = Modifier
                    .width(300.dp)
                    .height(200.dp)
                    .padding(bottom = 24.dp)
            )
        }

        Button(
            onClick = {
                if (!isLoading) {
                    isLoading = true
                    val dialog = AlertDialog.Builder(context)
                        .setTitle("提示信息")
                        .setMessage("正在下载中，请稍后……")
                        .setCancelable(false)
                        .create()
                    dialog.show()

                    Thread {
                        val bmp = downloadImage(imageUrl)
                        Handler(Looper.getMainLooper()).post {
                            bitmap = bmp
                            isLoading = false
                            dialog.dismiss()
                        }
                    }.start()
                }
            },
            enabled = !isLoading
        ) {
            Text("从网络上下载一张图片")
        }
    }
}